package com.hmyd.hmyd_android.ui;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dialog.SignInDialog;
import com.hmyd.hmyd_android.dto.SignDto;
import com.hmyd.hmyd_android.dto.SignPage;
import com.hmyd.hmyd_android.shop.JfMallActivity;
import com.hmyd.hmyd_android.view.ArcText;
import com.hmyd.hmyd_android.view.KCalendar;
import com.hmyd.hmyd_android.view.KCalendar.OnCalendarDateChangedListener;
import com.hmyd.hmyd_android.view.KCalendar.onKCalendarScrollListener;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 我的签到
 * 
 * @author wangc
 * 
 */
@ContentView(R.layout.activity_my_sign_in)
public class SignInActivity extends BasicActivity {
	// 标题栏
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;
	// 签到信息
	// @ViewInject(R.id.sign_msg)
	// private TextView mTvSignMsg;
	@ViewInject(R.id.sign_scores)
	private ArcText scoresImageView;
	@ViewInject(R.id.sign_total_score)
	private TextView mTvTotalScore;
	@ViewInject(R.id.my_sign_in_shop)
	private Button mSingInShop;
	@ViewInject(R.id.sign_msg)
	private TextView mTvNextDay;
	@ViewInject(R.id.sign_anim)
	private ImageView mIvAnim;

	// 日历
	private String date = null;// 设置默认选中的日期 格式为 “2014-04-05” 标准DATE格式
	private TextView popupwindow_calendar_month;
	private KCalendar calendar;
	private List<String> list = new ArrayList<String>(); // 设置标记列表
	private final int SIGIN = 1;
//	private final int USERINFO = 2;
	protected boolean hasMore = false;
	private String cursorId;
	private List<SignDto> datas = new ArrayList<SignDto>();// 服务器获取的日历信息

	@ViewInject(R.id.next)
	private ImageView nextMonth;
	@ViewInject(R.id.befor)
	private ImageView lastMonth;
//	private boolean isAnim = false;
	
	private SignInDialog dialog = null;

	@OnClick({ R.id.next, R.id.befor })
	public void onMonthClick(View view) {
		switch (view.getId()) {
		case R.id.next:
			calendar.nextMonth();
			RequestParams params = new RequestParams();
			params.addBodyParameter("gesture", "forward");
			params.addBodyParameter("lastCursor", cursorId);
			onRequest(SIGIN, UrlConstant.SIGIN, HttpMethod.POST, params);
			break;
		case R.id.befor:
			calendar.lastMonth();
			RequestParams params1 = new RequestParams();
			params1.addBodyParameter("gesture", "back");
			params1.addBodyParameter("lastCursor", cursorId);
			onRequest(SIGIN, UrlConstant.SIGIN, HttpMethod.POST, params1);
			break;

		default:
			break;
		}
	}

	@OnClick({ R.id.my_sign_in_shop })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.my_sign_in_shop:
			Intent intent = new Intent();
			intent.setClass(SignInActivity.this, JfMallActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

//		isAnim = getIntent().getBooleanExtra("isAnim", false);
		
		RequestParams params = new RequestParams();
		params.addBodyParameter("gesture", "hold");
		onRequest(SIGIN, UrlConstant.SIGIN, HttpMethod.POST, params);
//		onRequest(USERINFO, UrlConstant.GETMYINFO, HttpMethod.GET, null);

		popupwindow_calendar_month = (TextView) findViewById(R.id.popupwindow_calendar_month);
		calendar = (KCalendar) findViewById(R.id.popupwindow_calendar);
		popupwindow_calendar_month.setText(calendar.getCalendarYear() + "年"
				+ calendar.getCalendarMonth() + "月");
		if (null != date) {

			int years = Integer.parseInt(date.substring(0, date.indexOf("-")));
			int month = Integer.parseInt(date.substring(date.indexOf("-") + 1,
					date.lastIndexOf("-")));
			popupwindow_calendar_month.setText(years + "年" + month + "月");

			calendar.showCalendar(years, month);
			calendar.setCalendarDayBgColor(date, R.drawable.calendar_date_focused);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		/*
		 * “back”:获取本月之前5个月数据 "forward":获取本月之后5个月数据 "hold":获取本月单月数据
		 */
		
		setTextContent();
		if (!AppBasic.isCheckIned) {
			showAnim();
		}
	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		java.lang.reflect.Type type2 = new TypeToken<SignPage<SignDto>>() {
		}.getType();

		switch (postId) {
		/*case USERINFO:
			java.lang.reflect.Type type1 = new TypeToken<User>() {
			}.getType();
			User user = gson.fromJson(result, type1);
			mTvTotalScore.setText(NumberFormat.getInstance().format(AppBasic.totalScore) + "");
			if (user.isCheckIned) {
				// mTvSignMsg.setText("" + user.rewardScore);
				switch (user.rewardScore) {
				case 5:
					// scoresImageView.setImageResource(R.drawable.qiandao_img_huod5);
					scoresImageView.setScore("5");
					break;
				case 10:
					// scoresImageView.setImageResource(R.drawable.qiandao_img_huod10);
					scoresImageView.setScore("10");
					break;
				case 15:
					// scoresImageView.setImageResource(R.drawable.qiandao_img_huod15);
					scoresImageView.setScore("15");
					break;
				case 20:
					// scoresImageView.setImageResource(R.drawable.qiandao_img_huod20);
					scoresImageView.setScore("20");
					break;
				case 25:
					// scoresImageView.setImageResource(R.drawable.qiandao_img_huod25);
					scoresImageView.setScore("25");
					break;

				default:
					break;
				}
				mTvNextDay.setText(user.nextTimeScore + "");
			} else {
				// mTvSignMsg.setText("您今日还未签到");
				mTvNextDay.setVisibility(View.INVISIBLE);
			}

			if (isAnim) {
				dialog = new SignInDialog(this, R.style.calculatorDialog,
						user.rewardScore + "");
				CountDownTimer timer = new CountDownTimer(80 * 28, 80) {

					@Override
					public void onTick(long millisUntilFinished) {
						dialog.show();
					}

					@Override
					public void onFinish() {
						dialog.dismiss();
					}
				}.start();
			}
			break;*/
		case SIGIN:// TODO
			final SignPage<SignDto> page = gson.fromJson(result, type2);
			hasMore = page.hasMore;

			datas.addAll(page.records);
			for (int i = 0; i < datas.size(); i++) {
				String monthString = datas.get(i).date;
				String[] year = monthString.split("年");
				String[] month = year[1].split("月");
				String year_month = null;
				if (month[0].length() < 2) {
					year_month = year[0] + "-" + "0" + month[0] + "-";
				} else {
					year_month = year[0] + "-" + month[0] + "-";
				}

				List<String> checkInDays = datas.get(i).checkIn;
				for (int j = 0; j < checkInDays.size(); j++) {
					if (checkInDays.get(j).length() < 2) {
						list.add(year_month + "0" + checkInDays.get(j));
					} else {
						list.add(year_month + checkInDays.get(j));
					}
				}
				cursorId = datas.get(i).lastCursor;
			}

			calendar.addMarks(list, 0);

			// 监听当前月份
			calendar.setOnCalendarDateChangedListener(new OnCalendarDateChangedListener() {
				public void onCalendarDateChanged(int year, int month) {
					popupwindow_calendar_month.setText(year + "年" + month + "月");
				}
			});

			calendar.setOnKCalendarScrollListener(new onKCalendarScrollListener() {

				@Override
				public void onKCalendarScroll(String direction) {
					if (direction.equals("back") && page.hasTop) {
						RequestParams params = new RequestParams();
						params.addBodyParameter("gesture", "back");
						params.addBodyParameter("lastCursor", cursorId);
						onRequest(SIGIN, UrlConstant.SIGIN, HttpMethod.POST, params);
					} else if (direction.equals("forward") && page.hasMore) {
						RequestParams params = new RequestParams();
						params.addBodyParameter("gesture", "forward");
						params.addBodyParameter("lastCursor", cursorId);
						onRequest(SIGIN, UrlConstant.SIGIN, HttpMethod.POST, params);
					}
				}
			});

			break;

		default:
			break;
		}

	}

	@Override
	public void onPostFailure(int postId, String msg) {

	}
	
	private void setTextContent(){
		mTvTotalScore.setText(NumberFormat.getInstance().format(AppBasic.totalScore) + "");
//		if (AppBasic.isCheckIned) {
			/*if (AppBasic.rewardScore == 5) {
				// scoresImageView.setImageResource(R.drawable.qiandao_img_huod5);
				scoresImageView.setScore("5");
			} else if (AppBasic.rewardScore == 10) {
				// scoresImageView.setImageResource(R.drawable.qiandao_img_huod10);
				scoresImageView.setScore("10");
			} else if (AppBasic.rewardScore == 15) {
				// scoresImageView.setImageResource(R.drawable.qiandao_img_huod15);
				scoresImageView.setScore("15");
			} else if (AppBasic.rewardScore == 20) {
				// scoresImageView.setImageResource(R.drawable.qiandao_img_huod20);
				scoresImageView.setScore("20");
			} else if (AppBasic.rewardScore == 25) {
				// scoresImageView.setImageResource(R.drawable.qiandao_img_huod25);
				scoresImageView.setScore("25");
			} else {
			}*/
			
			scoresImageView.setScore(String.valueOf((int)AppBasic.rewardScore));
			
			mTvNextDay.setText((int)AppBasic.nextTimeScore + "");
//		} else {
//			// mTvSignMsg.setText("您今日还未签到");
//			mTvNextDay.setVisibility(View.INVISIBLE);
//		}
	}
	
	/**
	 * 动画展示
	 */
	private void showAnim(){
		dialog = new SignInDialog(this, R.style.calculatorDialog,
				(int)AppBasic.rewardScore + "");
		new CountDownTimer(80 * 28, 80) {

			@Override
			public void onTick(long millisUntilFinished) {
				dialog.show();
			}

			@Override
			public void onFinish() {
				dialog.dismiss();
			}
		}.start();
	}

	@Override
	protected void setParams() {
		home_title_txt.setText("我的签到");
		home_title.setOnTouchListener(touch);

	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (null != dialog && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}
	}
}
